﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Linq;
using System.Collections.Generic;

namespace cad
{
    public class PickAndStretch
    {
       
        public void pickAndstretch(PromptSelectionResult selectionResult)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            try
            {
                //// 提示用户选择多个图框区域（矩形或多段线）
                //PromptSelectionResult selectionResult = ed.GetSelection();
                //if (selectionResult.Status != PromptStatus.OK)
                //{
                //    ed.WriteMessage("没有选择任何对象。\n");
                //    return;
                //}

                // 遍历每个选中的图框
                foreach (ObjectId objId in selectionResult.Value.GetObjectIds())
                {
                    // 识别框框坐标范围
                    double minX = double.MaxValue;
                    double maxX = double.MinValue;
                    double minY = double.MaxValue;
                    double maxY = double.MinValue;

                    // 存储圆心坐标
                    var circleCenters = new List<Point3d>();

                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        Entity entity = trans.GetObject(objId, OpenMode.ForRead) as Entity;

                        // 如果是多段线（假设框框是多段线或矩形）
                        if (entity is Polyline polyline)
                        {
                            if (polyline.Closed && polyline.NumberOfVertices == 4)
                            {
                                // 获取多段线的四个角点，确定图框的坐标范围
                                for (int i = 0; i < polyline.NumberOfVertices; i++)
                                {
                                    Point3d pt = polyline.GetPoint3dAt(i);
                                    minX = Math.Min(minX, pt.X);
                                    maxX = Math.Max(maxX, pt.X);
                                    minY = Math.Min(minY, pt.Y);
                                    maxY = Math.Max(maxY, pt.Y);
                                }
                            }
                        }
                        trans.Commit();
                    }

                    // 输出图框的坐标范围
                    ed.WriteMessage($"\n图框的坐标范围：X({minX}, {maxX}), Y({minY}, {maxY})");

                    // 提取框内的圆心
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable blockTable = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord modelSpace = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                        // 遍历模型空间中的所有圆形对象
                        foreach (ObjectId objIdInModelSpace in modelSpace)
                        {
                            Entity entity = trans.GetObject(objIdInModelSpace, OpenMode.ForRead) as Entity;

                            // 只考虑圆形对象
                            if (entity is Circle circle)
                            {
                                Point3d center = circle.Center;

                                // 判断圆心是否在当前图框内
                                if (center.X >= minX && center.X <= maxX && center.Y >= minY && center.Y <= maxY)
                                {
                                    // 保存圆心坐标
                                    circleCenters.Add(center);
                                }
                            }
                        }
                        trans.Commit();
                    }

                    // 如果没有找到符合条件的圆形，提示用户
                    if (circleCenters.Count == 0)
                    {
                        ed.WriteMessage("\n没有找到符合条件的圆形。\n");
                        continue;  // 继续处理下一个图框
                    }

                    // 按 X 值排序，选择 X 值相邻之间间距最大的圆心
                    var sortedCircleCenters = circleCenters.OrderBy(c => c.X).ToList();

                    // 计算相邻圆心之间的间距
                    double maxDistance = 0;
                    Point3d selectedCenter = sortedCircleCenters[0];  // 默认选择第一个圆心
                    for (int i = 0; i < sortedCircleCenters.Count - 1; i++)
                    {
                        double distance = sortedCircleCenters[i + 1].X - sortedCircleCenters[i].X;
                        if (distance > maxDistance)
                        {
                            maxDistance = distance;
                            selectedCenter = sortedCircleCenters[i];  // 选择 X 值较小的圆心
                        }
                    }

                    // 输出选中的圆心坐标
                    ed.WriteMessage($"\n选择的圆心坐标: X={selectedCenter.X}, Y={selectedCenter.Y}");

                    // 计算新矩形的边界
                    double rightBoundary = selectedCenter.X+50 ;  // 新矩形右边界为选中圆心的X值
                    double leftBoundary = minX+0.1;  // 新矩形左边界与图框的左边界对齐
                    double topBoundary = maxY-0.1;  // 新矩形上边界与图框的上边界对齐
                    double bottomBoundary = minY+0.1;  // 新矩形下边界与图框的下边界对齐

                    // 创建新矩形的四个点
                    Point3d p1 = new Point3d(leftBoundary, topBoundary, 0);
                    Point3d p2 = new Point3d(leftBoundary, bottomBoundary, 0);
                    Point3d p3 = new Point3d(rightBoundary, bottomBoundary, 0);
                    Point3d p4 = new Point3d(rightBoundary, topBoundary, 0);

                    // 使用 SelectCrossingWindow 方法框选区域进行选择
                    PromptSelectionResult result = ed.SelectCrossingWindow(p1, p3);

                    if (result.Status == PromptStatus.OK)
                    {
                        // 选中区域内的物体
                        ObjectIdCollection selectedIdsCollection = new ObjectIdCollection(result.Value.GetObjectIds());

                        // 高亮显示选中的物体
                        ObjectId[] selectedIds = selectedIdsCollection.Cast<ObjectId>().ToArray();
                        ed.SetImpliedSelection(selectedIds);

                        // 执行拉伸操作（从 p1 开始，缩进单位）
                        ed.WriteMessage("\n执行拉伸操作，将选中的物体缩进。\n");
                        StretchType pickandstretch = new StretchType();
                        pickandstretch.StretchSelection(selectedIdsCollection, p1, maxDistance * 0.5, leftBoundary, rightBoundary, topBoundary, bottomBoundary);
                    }
                    else
                    {
                        ed.WriteMessage("\n没有选中任何对象。\n");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage($"\n发生异常：{ex.Message}");
            }
        }
    }
}
